package com.auto.survey.activity.bluetooth

import android.Manifest
import android.app.Service
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothProfile
import android.bluetooth.BluetoothServerSocket
import android.bluetooth.BluetoothSocket
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Binder
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.annotation.RequiresPermission
import com.auto.survey.log.AppLogger
import com.auto.survey.widget.CentreToast
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.lang.reflect.Method
import java.net.SocketTimeoutException
import java.util.Timer
import java.util.TimerTask
import java.util.UUID
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.CountDownLatch
import java.util.concurrent.ExecutionException
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException

class BluetoothService : Service() {

    private val TAG = BluetoothService::class.java.simpleName

    private val binder = LocalBinder()

    // 搜索状态管理
    private var isDiscovering = false
    private var currentReceiver: BroadcastReceiver? = null
    private var discoveryHandler: Handler? = null
    private var discoveryTimeoutRunnable: Runnable? = null

    private val handler = Handler(Looper.getMainLooper())
    private val connectionExecutor = Executors.newSingleThreadExecutor()

    // 使用固定线程池避免频繁创建线程
    private val scanExecutor = Executors.newFixedThreadPool(2)
    // 使用线程安全的列表
    private val deviceBuffer = CopyOnWriteArrayList<BluetoothDevice>()
    private var scanTimer: Timer? = null

    // 蓝牙管理相关
    private lateinit var bluetoothAdapter: BluetoothAdapter
    private val connectedSocketMap = mutableMapOf<BluetoothDevice, BluetoothSocket>()
    private val connectionStateMap = mutableMapOf<BluetoothDevice, ConnectionState>()
    private val connectDevices = mutableListOf<BluetoothDevice>()
    private lateinit var bluetoothManager:BluetoothManager
    // 设备列表和回调
    private val scannedDevices = mutableListOf<BluetoothDevice>()
    // 已配对设备列表
    private val pairedDevices = mutableListOf<BluetoothDevice>()

    // 回调接口列表
    private val callbacks = mutableListOf<ConnectionCallback>()

    // 定义连接状态枚举
    enum class ConnectionState {
        DISCONNECTED, CONNECTING, CONNECTED, DISCONNECTING
    }

    // 在BluetoothService类中添加
    private var isInitiatingConnection = false

    // 服务端相关
    private var serverSocket: BluetoothServerSocket? = null
    private var acceptThread: AcceptThread? = null
    private val serverDevices = mutableMapOf<BluetoothSocket, BluetoothDevice>()
    private val SERVER_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB") // SPP UUID
    private val SERVER_NAME = "BluetoothServer"

    interface ConnectionCallback {
        fun onDiscoverDeviceState(isdiscovery:Boolean)
        fun onConnectionStateChanged(device: BluetoothDevice, state: ConnectionState)
        fun onDataReceived(device: BluetoothDevice, data: ByteArray)
        fun onError(message: String)
    }

    // Binder类
    inner class LocalBinder : Binder() {
        val service: BluetoothService
            get() = this@BluetoothService
    }

    private val bluetoothReceiver = object : BroadcastReceiver() {
        override fun onReceive(p0: Context?, intent: Intent?) {
            val action = intent?.action
            when (action) {
                BluetoothDevice.ACTION_ACL_CONNECTED -> {

                    val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                    if (device != null && device.bondState == BluetoothDevice.BOND_BONDED) {
                        connectDevices.add(device)
                        //作为服务端接受客户端设备的连接请求
                        if (!isInitiatingConnection) {
                            startServer()
                        }

                    }

                }
                BluetoothDevice.ACTION_ACL_DISCONNECTED -> {
                    val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                    if (device != null && device.bondState == BluetoothDevice.BOND_BONDED) {
                        connectionStateMap[device] = ConnectionState.DISCONNECTED
                        connectDevices.clear()
                        notifyConnectionState(device, ConnectionState.DISCONNECTED)
                    }
                }

                BluetoothDevice.ACTION_PAIRING_REQUEST -> {
                    Log.i(TAG, "#####BluetoothDevice.ACTION_PAIRING_REQUEST#####")
                    val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                    handlePairingRequest(intent, device)
                }

            }
        }

    }

    override fun onCreate() {
        super.onCreate()

        registerReceiver(bluetoothReceiver, IntentFilter().apply {
            addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
            addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
            addAction(BluetoothDevice.ACTION_ACL_CONNECTED)
            addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED)
            addAction(BluetoothDevice.ACTION_PAIRING_REQUEST)
        })

        bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        bluetoothAdapter = bluetoothManager.adapter
    }

    override fun onBind(intent: Intent): IBinder = binder

    // 注册回调
    fun registerCallback(callback: ConnectionCallback) {
        if (!callbacks.contains(callback)) {
            callbacks.add(callback)
        }
    }

    // 注销回调
    fun unregisterCallback(callback: ConnectionCallback) {
        callbacks.remove(callback)
    }


    // 连接设备（仅经典蓝牙）
    @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
    fun connectDevice(device: BluetoothDevice) {
        isInitiatingConnection = true
        Log.i(TAG, "====connectDevice====")
        if (device.bondState != BluetoothDevice.BOND_BONDED) {
            Log.i(TAG, "开始尝试配对")
            device.createBond()
        } else {
            Log.d(TAG, "尝试连接到 ${device.name ?: device.address}")
            connectClassicDevice(device)
        }
    }

    //作为服务端接收蓝牙设备连接请求， 启动蓝牙服务器
    fun startServer() {
        if (serverSocket != null) {
            Log.d(TAG, "服务器已在运行中")
            return
        }

        if (!bluetoothAdapter.isEnabled) {
            Log.e(TAG, "蓝牙未启用，无法启动服务器")
            notifyError("蓝牙未启用，无法启动服务器")
            return
        }

        try {
            // 创建服务器套接字
            serverSocket = bluetoothAdapter.listenUsingRfcommWithServiceRecord(
                SERVER_NAME, SERVER_UUID
            )
            Log.d(TAG, "服务器已启动，等待连接...")
            notifyDiscoverDeviceState(true) // 表示正在监听

            // 启动接受连接的线程
            acceptThread = AcceptThread()
            acceptThread?.start()
        } catch (e: IOException) {
            Log.e(TAG, "启动服务器失败: ${e.message}", e)
            notifyError("启动服务器失败: ${e.message}")
        }
    }

    // 停止服务器
    fun stopServer() {
        acceptThread?.cancel()
        acceptThread = null

        serverSocket?.close()
        serverSocket = null

        // 关闭所有客户端连接
        serverDevices.keys.forEach { socket ->
            socket.closeSafely()
        }
        serverDevices.clear()

        Log.d(TAG, "服务器已停止")
        notifyDiscoverDeviceState(false)
    }

    // 接受连接的线程
    private inner class AcceptThread : Thread() {
        private var running = true

        override fun run() {
            while (running) {
                try {
                    Log.d(TAG, "等待客户端连接...")
                    val clientSocket = serverSocket?.accept() ?: break
                    Log.d(TAG, "客户端连接已接受: ${clientSocket.remoteDevice.name}")

                    // 获取客户端设备
                    val device = clientSocket.remoteDevice

                    // 添加到已连接设备列表
                    serverDevices[clientSocket] = device
                    connectDevices.add(device)

                    // 通知连接状态变化
                    connectionStateMap[device] = ConnectionState.CONNECTED
                    notifyConnectionState(device, ConnectionState.CONNECTED)

                    // 启动通信线程
                    val connectedThread = ConnectedThread(clientSocket, device)
                    connectedThread.start()

                } catch (e: IOException) {
                    if (running) {
                        Log.e(TAG, "接受连接失败: ${e.message}", e)
                        notifyError("接受连接失败: ${e.message}")
                    }
                    break
                }
            }
        }

        fun cancel() {
            running = false
            try {
                serverSocket?.close()
            } catch (e: IOException) {
                Log.e(TAG, "关闭服务器套接字失败: ${e.message}", e)
            }
        }
    }

    // 处理与客户端通信
    private inner class ConnectedThread(
        private val socket: BluetoothSocket,
        private val device: BluetoothDevice
    ) : Thread() {
        private val inputStream: InputStream?
        private val outputStream: OutputStream?
        private var running = true

        init {
            var tmpIn: InputStream? = null
            var tmpOut: OutputStream? = null

            try {
                tmpIn = socket.inputStream
                tmpOut = socket.outputStream
            } catch (e: IOException) {
                Log.e(TAG, "获取流失败: ${e.message}", e)
            }

            inputStream = tmpIn
            outputStream = tmpOut
        }

        override fun run() {
            val buffer = ByteArray(1024)
            var bytes: Int

            // 持续监听输入流
            while (running) {
                try {
                    bytes = inputStream?.read(buffer) ?: -1
                    if (bytes > 0) {
                        val data = buffer.copyOfRange(0, bytes)
                        // 处理接收到的数据
                        Log.i(TAG, "收到数据：${data.toString()}")
                        notifyDataReceived(device, data)
                    }
                } catch (e: IOException) {
                    Log.w(TAG, "客户端断开连接: ${e.message}")
                    running = false
                    break
                }
            }

            // 连接断开后清理资源
            disconnectDevice(device)
            socket.closeSafely()
            serverDevices.remove(socket)
        }

        // 向客户端发送数据
        fun write(data: ByteArray) {
            try {
                outputStream?.write(data)
                Log.d(TAG, "向客户端发送数据: ${String(data)}")
            } catch (e: IOException) {
                Log.e(TAG, "发送数据失败: ${e.message}", e)
                running = false
            }
        }

        fun cancel() {
            running = false
            try {
                socket.close()
            } catch (e: IOException) {
                Log.e(TAG, "关闭客户端套接字失败: ${e.message}", e)
            }
        }
    }

    // 服务端发送数据到指定客户端
    fun sendDataToClient(device: BluetoothDevice, data: ByteArray) {
        serverDevices.entries.find { it.value == device }?.key?.let { socket ->
            connectionExecutor.execute {
                try {
                    Log.i(TAG, "尝试向${device.name}, mac:${device.address} 发送数据")
                    if (socket.isConnected) {
                        Log.i(TAG, "开始向${device.name}, mac:${device.address} 发送数据：${data.toString()}")
                        socket.outputStream.write(data)
                    } else {
                        Log.w(TAG, "客户端已断开连接")
                    }
                } catch (e: IOException) {
                    Log.e(TAG, "发送数据失败: ${e.message}", e)
                }
            }
        } ?: run {
            Log.w(TAG, "未找到对应的客户端连接")
        }
    }

    // 断开指定客户端连接（服务端）
    fun disconnectClient(device: BluetoothDevice) {
        serverDevices.entries.find { it.value == device }?.key?.let { socket ->
            socket.closeSafely()
            serverDevices.remove(socket)
            connectDevices.remove(device)
            connectionStateMap[device] = ConnectionState.DISCONNECTED
            notifyConnectionState(device, ConnectionState.DISCONNECTED)
        }
    }

    // 连接经典蓝牙设备（优化版）
    @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
    private fun connectClassicDevice(device: BluetoothDevice) {
        if (connectionStateMap[device] == ConnectionState.CONNECTED) {
            Log.d(TAG, "设备已连接: ${device.name ?: device.address}")
            return
        }

        connectionStateMap[device] = ConnectionState.CONNECTING
        notifyConnectionState(device, ConnectionState.CONNECTING)

        connectionExecutor.execute {
            var socket: BluetoothSocket? = null
            var success = false

            try {
                socket = createCompatibleSocket(device) ?: throw IOException("无法创建Socket")

                if (connectWithTimeout(socket, 20000)) {
                    Log.d(TAG, "连接成功: ${device.name ?: device.address}")

                    // 在添加到map前先设置输入流监听器
                    setupSocketListener(device, socket)

                    connectedSocketMap[device] = socket
                    connectDevices.add(device)
                    connectionStateMap[device] = ConnectionState.CONNECTED
                    notifyConnectionState(device, ConnectionState.CONNECTED)
                    success = true
                } else {
                    isInitiatingConnection = false
                    Log.d(TAG, "连接超时: ${device.name ?: device.address}")
                    throw IOException("连接超时")
                }

            } catch (e: IOException) {
                isInitiatingConnection = false
                Log.e(TAG, "连接失败: ${e.message}", e)
                connectionStateMap[device] = ConnectionState.DISCONNECTED
                notifyConnectionState(device, ConnectionState.DISCONNECTED)
                notifyError("连接失败: ${e.message}")
            } finally {
                if (!success) {
                    socket?.closeSafely()
                }
            }
        }
    }

    // 创建兼容的Socket（优化版，移除BLE相关逻辑）
    private fun createCompatibleSocket(device: BluetoothDevice): BluetoothSocket? {
        try {
            // 尝试标准UUID连接
            val uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")
            return device.createRfcommSocketToServiceRecord(uuid)
        } catch (e: IOException) {
            Log.w(TAG, "标准UUID连接失败，尝试反射方法: ${e.message}")
        }

        // 反射创建RFCOMM socket (无需预先查询通道)
        return try {
            val method = device.javaClass.getMethod("createRfcommSocket", Int::class.java)
            method.invoke(device, 1) as BluetoothSocket // 默认使用通道1
        } catch (e: Exception) {
            Log.e(TAG, "反射创建失败", e)
            null
        }
    }

    // 带超时的连接（优化版，移除同步等待）
    @RequiresApi(Build.VERSION_CODES.N)
    private fun connectWithTimeout(socket: BluetoothSocket, timeoutMillis: Long): Boolean {
        val future = CompletableFuture<Boolean>()
        var connectionThread: Thread? = null

        try {
            connectionThread = Thread {
                try {
                    socket.connect()
                    future.complete(true)
                } catch (e: SocketTimeoutException) {
                    AppLogger.getInstance(this@BluetoothService).w(TAG, "连接超时: ${e.message}")
                    future.complete(false)
                } catch (e: IOException) {
                    AppLogger.getInstance(this@BluetoothService).e(TAG, "连接失败: ${e.message}", e)
                    future.complete(false)
                } catch (e: Exception) {
                    // 捕获其他异常，确保线程不会意外终止
                    AppLogger.getInstance(this@BluetoothService).e(TAG, "连接过程异常: ${e.message}", e)
                    future.complete(false)
                }
            }

            connectionThread.isDaemon = true
            connectionThread.start()

            return future.get(timeoutMillis, TimeUnit.MILLISECONDS)
        } catch (e: TimeoutException) {
            AppLogger.getInstance(this@BluetoothService).w(TAG, "连接操作超时")

            // 尝试关闭socket以释放资源
            try {
                socket.close()
                AppLogger.getInstance(this@BluetoothService).d(TAG, "已关闭超时的socket连接")
            } catch (closeEx: IOException) {
                AppLogger.getInstance(this@BluetoothService).e(TAG, "关闭socket失败: ${closeEx.message}")
            }

            return false
        } catch (e: ExecutionException) {
            // 处理连接过程中抛出的异常
            val cause = e.cause
            if (cause is IOException) {
                AppLogger.getInstance(this@BluetoothService).e(TAG, "连接失败: ${cause.message}", cause)
            } else {
                AppLogger.getInstance(this@BluetoothService).e(TAG, "连接执行异常: ${e.message}", e)
            }
            return false
        } catch (e: InterruptedException) {
            // 恢复中断状态
            Thread.currentThread().interrupt()
            AppLogger.getInstance(this@BluetoothService).w(TAG, "连接操作被中断")

            // 关闭socket
            try {
                socket.close()
            } catch (closeEx: IOException) {
                AppLogger.getInstance(this@BluetoothService).e(TAG, "关闭socket失败: ${closeEx.message}")
            }

            return false
        } finally {
            // 确保线程引用被清除
            connectionThread = null
        }
    }

    // 设置Socket输入流监听器
    private fun setupSocketListener(device: BluetoothDevice, socket: BluetoothSocket) {
        connectionExecutor.execute {
            try {
                val inputStream = socket.inputStream
                val buffer = ByteArray(1024)
                var bytes: Int

                // 持续监听输入流，直到连接断开
                while (socket.isConnected) {
                    bytes = inputStream.read(buffer)
                    if (bytes > 0) {
                        val data = buffer.copyOfRange(0, bytes)
                        // 处理接收到的数据
                        notifyDataReceived(device, data)
                    }
                }
            } catch (e: IOException) {
                Log.w(TAG, "连接断开: ${e.message}")
                // 从已连接列表移除
                disconnectDevice(device)
            }
        }
    }

    // 安全关闭socket
    private fun BluetoothSocket?.closeSafely():Boolean {
        try {
            this?.close()
            Log.e(TAG, "关闭socket成功:")
            return true
        } catch (e: IOException) {
            Log.e(TAG, "关闭socket失败: ${e.message}")
            return false
        }
    }

    // 断开设备连接
    @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
    fun disconnectDevice(device: BluetoothDevice) {
        Log.i(TAG, "disconnectDevice")
        connectionStateMap[device] = ConnectionState.DISCONNECTING
        notifyConnectionState(device, ConnectionState.DISCONNECTING)

        connectionExecutor.execute {
            try {

                if (connectedSocketMap[device]?.closeSafely() == true) {
                    connectDevices.clear()
                    connectedSocketMap.remove(device)
                    connectionStateMap[device] = ConnectionState.DISCONNECTED
                    notifyConnectionState(device, ConnectionState.DISCONNECTED)
                }

            } catch (e: Exception) {
                Log.e("BluetoothService", "断开连接失败: ${e.message}", e)
                notifyError("断开连接失败: ${e.message}")
            }
        }
    }

    // 发送数据
    @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
    fun sendData(device: BluetoothDevice, data: ByteArray) {
        connectionExecutor.execute {
            try {
                val socket = connectedSocketMap[device]
                if (socket != null && socket.isConnected) {
                    socket.outputStream.write(data)
                } else {
                    notifyError("设备未连接或连接已断开")
                }
            } catch (e: Exception) {
                Log.e("BluetoothService", "发送数据失败: ${e.message}", e)
                notifyError("发送数据失败: ${e.message}")
            }
        }
    }

    // 获取已连接设备列表
    @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
    fun getConnectedDevices(): List<BluetoothDevice> {
        return connectedSocketMap.keys.toList()
    }

    fun getConnectedDevices2():List<BluetoothDevice> {
        return connectDevices
    }

    // 通过反射检查设备是否已连接
    suspend fun isInitDeviceConnected(): String {
        try {

            // 等待所有配置文件查询完成
            val latch = CountDownLatch(4) // A2DP, HEADSET, GATT, HID
            val connectedDevices = mutableListOf<BluetoothDevice>()

            // 检测 A2DP 设备（音频输出）
            getConnectedDevicesByProfile(bluetoothAdapter, BluetoothProfile.A2DP) { devices ->
                connectedDevices.addAll(devices)
                latch.countDown()
            }

            // 检测 HEADSET 设备（语音通信）
            getConnectedDevicesByProfile(bluetoothAdapter, BluetoothProfile.HEADSET) { devices ->
                connectedDevices.addAll(devices)
                latch.countDown()
            }

            // 检测 GATT 设备（BLE 设备）
            getConnectedDevicesByProfile(bluetoothAdapter, BluetoothProfile.GATT) { devices ->
                connectedDevices.addAll(devices)
                latch.countDown()
            }

            // 检测 HID 设备（键盘、鼠标等输入设备）
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                getConnectedDevicesByProfile(bluetoothAdapter, BluetoothProfile.HID_DEVICE) { devices ->
                    connectedDevices.addAll(devices)
                    latch.countDown()
                }
            } else {
                latch.countDown() // 如果版本不支持，直接计数
            }


            // 等待所有查询完成（最多5秒）
            try {
                latch.await(5, TimeUnit.SECONDS)
            } catch (e: InterruptedException) {
                Log.e(TAG, "蓝牙查询超时")
            }

            // 去重并显示结果
            val uniqueDevices = connectedDevices.distinctBy { it.address }

            if (uniqueDevices.isNotEmpty()) {
                connectDevices.addAll(uniqueDevices)
                val deviceNames = uniqueDevices.joinToString("\n") {
                    "${it.name ?: "未知设备"} (${it.address})"
                }

                return deviceNames
            } else {
                return ""
            }

        } catch (e: java.lang.Exception) {
            Log.e(TAG, "获取连接状态失败: " + e.message)
            return ""
        }
    }


    // 通过指定配置文件获取连接设备（异步方法）
    private fun getConnectedDevicesByProfile(bluetoothAdapter: BluetoothAdapter, profile: Int,
        callback: (List<BluetoothDevice>) -> Unit
    ) {

        bluetoothAdapter.getProfileProxy(this, object : BluetoothProfile.ServiceListener {
            override fun onServiceConnected(profileId: Int, proxy: BluetoothProfile) {
                try {
                    val devices = proxy.connectedDevices
                    Log.d(TAG, "Profile $profileId 连接设备: ${devices.size}")
                    callback(devices)
                } finally {
                    // 释放代理
                    bluetoothAdapter.closeProfileProxy(profileId, proxy)
                }
            }

            override fun onServiceDisconnected(profileId: Int) {
                callback(emptyList())
            }
        }, profile)
    }

    // 获取已配对设备列表
    @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
    fun getPairedDevices(callback: (MutableList<BluetoothDevice>) -> Unit) {

        if (!bluetoothAdapter.isEnabled) return

        // 优化：在后台线程获取已配对设备，避免主线程卡顿
        Executors.newSingleThreadExecutor().execute {
            bluetoothAdapter.bondedDevices?.let { devices ->
                synchronized(this) {
                    pairedDevices.clear()
                    pairedDevices.addAll(devices)
                    Log.d(TAG, "获取到 ${devices.size} 个已配对设备")

                    // 切换到主线程通知UI
                    handler.post {
                        callback.invoke(pairedDevices)
                    }
                }
            }
        }
    }


    // 开始搜索设备
    @RequiresPermission(Manifest.permission.BLUETOOTH_SCAN)
    fun startDiscovery(callback: (MutableList<BluetoothDevice>) -> Unit) {

        Log.i(TAG, "===startDiscovery===")
        if (!bluetoothAdapter.isEnabled) {
            Log.w(TAG, "蓝牙未启用，无法搜索")
            return
        }

        // 如果正在搜索，先停止当前搜索
        if (isDiscovering) {
            CentreToast.instance.showText("正在搜索设备，请稍后刷新")
            return
        }
        notifyDiscoverDeviceState(true)
        isDiscovering = true
        deviceBuffer.clear()

        // 创建新的Handler和Runnable
        discoveryHandler = Handler(Looper.getMainLooper())
        discoveryTimeoutRunnable = Runnable {
            Log.i(TAG, "===延迟任务触发 stopDiscovery===")
            // 检查状态，避免不必要的调用
            if (isDiscovering) {
                stopDiscovery(callback)
            }
        }

        val filter = IntentFilter(BluetoothDevice.ACTION_FOUND)
        val receiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                if (intent.action == BluetoothDevice.ACTION_FOUND) {
                    val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                    device?.let {

                        scanExecutor.execute {
                            Log.d(TAG, "发现设备: ${device.name ?: device.address}")
                            if (!scannedDevices.contains(it)) {
                                deviceBuffer.add(it)
                            }
                            scheduleBufferProcessing(callback)
                        }
                    }
                }
            }
        }
        currentReceiver = receiver
        registerReceiver(receiver, filter)

        // 设置延迟任务，使用保存的Handler
        discoveryHandler?.postDelayed(discoveryTimeoutRunnable!!, 12000)

        bluetoothAdapter.startDiscovery()
    }

    fun disableBluetooth(call:(Boolean) -> Unit) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            call.invoke(false)
            return
        }
        if (bluetoothAdapter.isEnabled) {
            val success = bluetoothAdapter.disable()
            call.invoke(success)
        }
    }

    // 获取当前蓝牙状态
    fun getBluetoothState(): Int {
        return bluetoothAdapter.state
    }

    // 合并定时器逻辑，避免重复代码
    private fun scheduleBufferProcessing(callback: (MutableList<BluetoothDevice>) -> Unit) {
        // 如果缓冲区达到阈值，立即处理
        if (deviceBuffer.size >= 3) {
            Log.d("Bluetooth", "缓冲区达到阈值，立即处理")
            processDeviceBuffer(callback)
            return
        }

        // 否则延迟处理
        scanTimer?.cancel()
        scanTimer = Timer().apply {
            schedule(object : TimerTask() {
                override fun run() {
                    Log.d("Bluetooth", "定时器触发，处理缓冲区")
                    processDeviceBuffer(callback)
                }
            }, 500)
        }
    }

    // 提取公共处理逻辑
    private fun processDeviceBuffer(callback: (MutableList<BluetoothDevice>) -> Unit) {
        val devices = ArrayList(deviceBuffer)
        if (devices.isNotEmpty()) {
            deviceBuffer.removeAll(devices)
            handler.post {
                scannedDevices.addAll(devices)
                callback(scannedDevices)
                Log.i(TAG, "扫描到的设备数量是：scannedDevices.size = ${scannedDevices.size}")
            }
        }
    }


    // 停止搜索设备
    @RequiresPermission(Manifest.permission.BLUETOOTH_SCAN)
    fun stopDiscovery(callback: (MutableList<BluetoothDevice>) -> Unit) {
        try {
            Log.i(TAG, "===stopDiscovery===")
            // 清除搜索状态
            clearDiscoveryState()
            // 清空设备缓冲区并触发UI更新
            synchronized(this) {
                if (deviceBuffer.isNotEmpty()) {
                    val remainingDevices = ArrayList(deviceBuffer)
                    deviceBuffer.clear()
                    scannedDevices.addAll(remainingDevices)
                    callback.invoke(scannedDevices)
                    Log.i(TAG, "停止搜索设备数量是：scannedDevices.size = ${scannedDevices.size}")
                }
            }
        } catch (e: IllegalArgumentException) {
            Log.w("BluetoothService", "尝试注销未注册的接收器", e)
        }

        if (bluetoothAdapter.isDiscovering) {
            bluetoothAdapter.cancelDiscovery()
        }
        // 更新搜索状态
        isDiscovering = false
    }

    // 清除搜索状态（私有方法，确保状态一致性）
    private fun clearDiscoveryState() {
        Log.i(TAG, "===clearDiscoveryState===")
        // 重置搜索标志
        isDiscovering = false
        notifyDiscoverDeviceState(false)
        // 移除所有延迟任务
        discoveryHandler?.removeCallbacksAndMessages(null)
        discoveryHandler = null
        discoveryTimeoutRunnable = null

        // 停止并清理定时器
        scanTimer?.cancel()
        scanTimer = null

        // 注销当前接收器
        currentReceiver?.let {
            try {
                unregisterReceiver(it)
            } catch (e: IllegalArgumentException) {
                Log.w(TAG, "尝试注销未注册的接收器", e)
            }
            currentReceiver = null
        }
    }

    // 处理配对请求（兼容不同Android版本）
    private fun handlePairingRequest(intent: Intent, pairingDevice:BluetoothDevice?) {
        Log.i(TAG, "处理配对请求（兼容不同Android版本）")
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return

        try {
            val pairingVariant = intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT,
                BluetoothDevice.ERROR)

            // 不同配对类型的处理
            when (pairingVariant) {
                BluetoothDevice.PAIRING_VARIANT_PIN -> {
                    // PIN码配对
                    Log.d(TAG, "PIN码配对请求")
                    setPairingPin(pairingDevice!!, "0000")
                }

                BluetoothDevice.PAIRING_VARIANT_PASSKEY_CONFIRMATION -> {
                    // 密码确认
                    val passkey = intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_KEY, 0)
                    Log.d(TAG, "密码确认请求: $passkey")
                    confirmPairing(pairingDevice!!, true)
                }

                4 -> {
                    // 显示密码
                    val displayPasskey = intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_KEY, 0)
                    Log.d(TAG, "显示密码: $displayPasskey")
                }

                5 -> {
                    // 简单确认配对
                    Log.d(TAG, "配对确认请求")
                    confirmPairing(pairingDevice!!, true)
                }
            }

            // 不再调用abortBroadcast()，让系统处理配对对话框
            // abortBroadcast() // 移除这行代码
        } catch (e: Exception) {
            Log.e(TAG, "处理配对请求失败: ${e.message}")
        }
    }



    // 通过反射设置配对PIN码
    private fun setPairingPin(device: BluetoothDevice, pin: String) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                // Android 4.4+ 使用setPin方法
                val setPinMethod: Method = BluetoothDevice::class.java.getMethod("setPin", ByteArray::class.java)
                setPinMethod.invoke(device, pin.toByteArray())
            }
        } catch (e: java.lang.Exception) {
            Log.e(TAG, "设置PIN码失败: " + e.message)
        }
    }

    // 通过反射确认配对
    private fun confirmPairing(device: BluetoothDevice, confirm: Boolean) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                // Android 4.4+ 使用setPairingConfirmation方法
                val setPairingConfirmation = BluetoothDevice::class.java.getMethod(
                    "setPairingConfirmation", Boolean::class.javaPrimitiveType
                )
                setPairingConfirmation.invoke(device, confirm)
            }
        } catch (e: java.lang.Exception) {
            Log.e(TAG, "确认配对失败: " + e.message)
        }
    }


    // 通知所有注册的回调
    private fun notifyConnectionState(device: BluetoothDevice, state: ConnectionState) {
        handler.post {
            callbacks.forEach { it.onConnectionStateChanged(device, state) }
        }
    }

    private fun notifyDiscoverDeviceState(isdiscovery:Boolean){
        Log.i(TAG, "===notifyDiscoverDeviceState===$isdiscovery")
        handler.post {
            callbacks.forEach { it.onDiscoverDeviceState(isdiscovery) }
        }
    }

    private fun notifyDataReceived(device: BluetoothDevice, data: ByteArray) {
        handler.post {
            callbacks.forEach { it.onDataReceived(device, data) }
        }
    }

    private fun notifyError(message: String) {
        handler.post {
            callbacks.forEach { it.onError(message) }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        disconnectAllDevices()
        stopServer()
        connectionExecutor.shutdownNow()
        unregisterReceiver(bluetoothReceiver)
        Log.d(TAG, "蓝牙服务已销毁")
    }

    // 断开所有连接
    fun disconnectAllDevices() :Boolean{
        var tempdis = false
        connectedSocketMap.values.forEach { tempdis = it.closeSafely() }

        if (tempdis) {
            connectedSocketMap.clear()
            connectionStateMap.clear()
            connectDevices.clear()
        }

        return tempdis

    }
}